package com.lingxu.api.utils;

import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.log4j.Log4j2;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DbFieldMetaUtil
 * @Description 描述
 * @Author junyi.wang
 * @Date 2025/7/21 17:28
 */

public class DbFieldMetaUtil {
    private static final Logger log = LoggerFactory.getLogger(DbFieldMetaUtil.class);

    /**
     * 获取达梦数据库表的字段字符长度映射（数据库列名→字符数）
     * @param dataSource 数据源（需注入Spring）
     * @param tableName 目标表名（达梦表名可能区分大小写，需与实际一致）
     * @return 字段字符长度映射
     */
    public static Map<String, Integer> getFieldCharLengths(DataSource dataSource, String tableName) {
        Map<String, Integer> fieldCharLengths = new HashMap<>();
        Connection conn = null;
        try {
            // 获取数据库连接
            conn = DataSourceUtils.getConnection(dataSource);
            DatabaseMetaData metaData = conn.getMetaData();

            ResultSet columns = metaData.getColumns(null, "DIMENMODEL", tableName, null);

            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME").toLowerCase();
                int charLength = columns.getInt("COLUMN_SIZE");
                fieldCharLengths.put(columnName, charLength);

            }
            columns.close();
        } catch (SQLException e) {
            log.error("达梦数据库获取表[{}]字段信息失败");
        } finally {
            if (conn != null) {
                DataSourceUtils.releaseConnection(conn, dataSource);
            }
        }
        return fieldCharLengths;
    }
}
